import React, { PureComponent } from 'react';
import { Input, Icon, InputNumber } from 'antd';
import styles from './index.less';

/**
 *  Describe:必须要给key不然更新就出事
 *  Created by xjc on 2019/6/20
 */

export default class EditableItem extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      value: props.value,
      editable: false,
    };
  }

  handleChange = e => {
    const { numberIF } = this.props;
    let value;
    if (numberIF) {
      value = e;
      this.setState({ value });
    } else {
      value = e.target;
      this.setState({ value });
    }
  };

  check = () => {
    this.setState({ editable: false });
    const { value } = this.state;
    const { onChange, row } = this.props;
    if (onChange) {
      const flag = onChange(value, row);
      if (!flag) {
        this.setState({ value: row.newprice });
      }
    }
  };

  edit = () => {
    this.setState({ editable: true });
  };

  render() {
    const { value, editable } = this.state;
    const { numberIF, placeholder, aftervalue } = this.props;
    return (
      <div className={styles.editableItem}>
        {editable ? (
          <div className={styles.wrapper}>
            {numberIF ? (
              <InputNumber
                style={{ width: '85%' }}
                placeholder={placeholder || ''}
                min={0}
                value={value}
                formatter={value => {
                  return `${value}`
                    .replace(/[^0-9\.]/gi, '')
                    .replace(/^(\-)*(\d+)\.(\d\d\d).*$/, '$1$2.$3');
                }} /* .match(/\d{1,9}\.\d{1,3}/)[0]}} */
                onChange={this.handleChange}
                onPressEnter={this.check}
              />
            ) : (
              <Input
                value={value}
                placeholder={placeholder || ''}
                onChange={this.handleChange}
                onPressEnter={this.check}
              />
            )}
            <Icon type="check" className={styles.icon} onClick={this.check} />
          </div>
        ) : (
          <div className={styles.wrapper}>
            <span>
              {(typeof value === 'undefined' || value === null || value === '' ? '' : value) +
                aftervalue}
            </span>
            <Icon type="edit" className={styles.icon} onClick={this.edit} />
          </div>
        )}
      </div>
    );
  }
}
